package cn.sxt.clinic.controller;

import cn.sxt.clinic.pojo.*;
import cn.sxt.clinic.service.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-29
 */
@Controller
@RequestMapping("/procurement")
public class ProcurementController {
    
    @Autowired
    private IProcurementTmpService procurementTmpService;

    @Autowired
    private IWarehousingAuditService warehousingAuditService;

    @Autowired
    private IMedicineInfoService medicineInfoService;

    @Autowired
    private IProcurementService procurementService;
    
    @Autowired
    private ISupplierService supplierService;

    @RequiresPermissions("procurement:procurementManager")
    @RequestMapping("/procurementManager")
    public String procurementManager(Model model,HttpSession session){
        List<Supplier> suppliers= supplierService.list();
        Random random = new Random();
        String result="";
        for (int i=0;i<15;i++)
        {
            result+=random.nextInt(10);
        }
        Procurement procurement=new Procurement();
        procurement.setOddNumbers(result);

        model.addAttribute("oddNumbers",procurement.getOddNumbers());
        model.addAttribute("suppliers",suppliers);
        return "procurementManager";
    }

    @RequestMapping("/computer")
    @ResponseBody
    public TotalAmout computer(){
        List<Procurement> list = procurementService.list();
        TotalAmout totalAmout=new TotalAmout();
        Float A=0.0f;
        Float B=0.0f;
        for (Procurement procurement : list) {
            A+=procurement.getProcurementWholesaleAmount();
            B+=procurement.getProcurementPrescriptionAmount();
        }
        totalAmout.setTotalWholesaleAmount(A);
        totalAmout.setTotalAmountPrescription(B);
        return totalAmout;
    }

    @RequestMapping("/procurementToAdd")
    public String procurementAdd(){
        return "procurementAdd";
    }

    @RequiresPermissions("procurement:list")
    @RequestMapping("/list")
    @ResponseBody
    public Map<String,Object> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "10") Integer pageSize){
        IPage<Procurement> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Procurement> wrapper = new QueryWrapper<>();
        IPage<Procurement> result = procurementService.page(page, wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",result.getTotal());
        map.put("rows",result.getRecords());
        return map;
    }

    @RequiresPermissions("procurement:examine")
    @RequestMapping("/examine")
    @ResponseBody
    public ResultCode examine(String oddNumbers, Date billingDate, Long supplierId, Long totalAmount, HttpSession session){
        Supplier supplier= supplierService.getById(supplierId);
        Doctor doctor = (Doctor) session.getAttribute("doctor");

        //为审核表对象设值
        WarehousingAudit warehousingAudit=new WarehousingAudit();
        warehousingAudit.setAuditProcurement(doctor.getRealname());
        warehousingAudit.setAuditMakeNumber(Long.parseLong(oddNumbers));
        warehousingAudit.setAuditPurchaseDate(billingDate);
        warehousingAudit.setAuditPurchaseAmount((float)totalAmount);
        warehousingAudit.setSupplier(supplier.getSupplier());
        warehousingAudit.setAuditReviewerDate(LocalDate.now());
        warehousingAudit.setStatus(0l);

        //删除采购入库表之前，复制一份完整数据
        List<Procurement> list = procurementService.list();
        List<Long> ids = new ArrayList<>();
        List<ProcurementTmp> procurementTmpList = new ArrayList<>();
        for (Procurement procurement : list) {
            ProcurementTmp procurementTmp = new ProcurementTmp();
            procurementTmp.setMakeNumber(Long.parseLong(oddNumbers));
            procurementTmp.setMedicineName(procurement.getMedicineName());
            procurementTmp.setUnit(procurement.getUnit());
            procurementTmp.setSpecs(procurement.getSpecs());
            procurementTmp.setProcurementNumber(procurement.getProcurementNumber());
            procurementTmp.setProcurementWholesalePrice(procurement.getProcurementWholesalePrice());
            procurementTmp.setProcurementPrescriptionPrice(procurement.getProcurementPrescriptionPrice());
            procurementTmp.setProcurementWholesaleAmount(procurement.getProcurementWholesaleAmount());
            procurementTmp.setProcurementPrescriptionAmount(procurement.getProcurementPrescriptionAmount());

            procurementTmpList.add(procurementTmp);

            //将采购表的数据id取出来
            ids.add(procurement.getProcurementId());
        }
        //将采购表的数据全部插入到影子表
        procurementTmpService.saveBatch(procurementTmpList);

        //清空采购表
        boolean b = procurementService.removeByIds(ids);

        //将设置好的审核数据插入到审核表
        boolean save = warehousingAuditService.save(warehousingAudit);
        ResultCode resultCode=null;
        if (save&&b){
            resultCode=new ResultCode(1,"提交成功");
        }else{
            resultCode=new ResultCode(0,"提交审核失败,请检查药品数据");
        }
        return resultCode;
    }

    @RequiresPermissions("procurement:warehousing")
    @RequestMapping("/warehousing")
    @ResponseBody
    public ResultCode warehousing(String oddNumbers, Date billingDate, Long supplierId, Long totalAmount, HttpSession session){
        Supplier supplier= supplierService.getById(supplierId);
        Doctor doctor = (Doctor) session.getAttribute("doctor");

        //为审核表对象设值
        WarehousingAudit warehousingAudit=new WarehousingAudit();
        warehousingAudit.setAuditProcurement(doctor.getRealname());
        warehousingAudit.setAuditMakeNumber(Long.parseLong(oddNumbers));
        warehousingAudit.setAuditPurchaseDate(billingDate);
        warehousingAudit.setAuditPurchaseAmount((float)totalAmount);
        warehousingAudit.setSupplier(supplier.getSupplier());
        warehousingAudit.setAuditReviewer(doctor.getRealname());
        warehousingAudit.setAuditReviewerDate(LocalDate.now());
        warehousingAudit.setStatus(1l);

        //删除采购入库表之前，复制一份完整数据
        List<Procurement> list = procurementService.list();
        List<Long> ids = new ArrayList<>();
        List<ProcurementTmp> procurementTmpList = new ArrayList<>();
        for (Procurement procurement : list) {
            ProcurementTmp procurementTmp = new ProcurementTmp();
            procurementTmp.setMakeNumber(Long.parseLong(oddNumbers));
            procurementTmp.setMedicineName(procurement.getMedicineName());
            procurementTmp.setUnit(procurement.getUnit());
            procurementTmp.setSpecs(procurement.getSpecs());
            procurementTmp.setProcurementNumber(procurement.getProcurementNumber());
            procurementTmp.setProcurementWholesalePrice(procurement.getProcurementWholesalePrice());
            procurementTmp.setProcurementPrescriptionPrice(procurement.getProcurementPrescriptionPrice());
            procurementTmp.setProcurementWholesaleAmount(procurement.getProcurementWholesaleAmount());
            procurementTmp.setProcurementPrescriptionAmount(procurement.getProcurementPrescriptionAmount());

            procurementTmpList.add(procurementTmp);

            //将采购表的数据id取出来
            ids.add(procurement.getProcurementId());
        }
        //将采购表的数据全部插入到影子表
        procurementTmpService.saveBatch(procurementTmpList);

        //清空采购表
        boolean b = procurementService.removeByIds(ids);

        //将设置好的审核数据插入到审核表
        boolean save = warehousingAuditService.save(warehousingAudit);

        Long auditId = warehousingAudit.getAuditId();

        //添加数据到库存表
        QueryWrapper<ProcurementTmp> wrapper = new QueryWrapper<>();
        wrapper.eq("make_number",oddNumbers);
        List<ProcurementTmp> ProcurementTmps = procurementTmpService.list(wrapper);
        for (ProcurementTmp procurementTmp : ProcurementTmps) {
            Stock stock = new Stock();
            stock.setMedicineName(procurementTmp.getMedicineName());
            stock.setDictionarySpecs(procurementTmp.getSpecs());
            QueryWrapper<MedicineInfo> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("medicine_name",procurementTmp.getMedicineName());
            MedicineInfo medicineInfo = medicineInfoService.getOne(queryWrapper);
            stock.setDictionaryType(medicineInfo.getDictionaryType());
            stock.setStockNumber(procurementTmp.getProcurementNumber().intValue());
            stock.setWholesalePrice(procurementTmp.getProcurementWholesalePrice());
            stock.setPrescriptionPrice(procurementTmp.getProcurementPrescriptionPrice());
            stock.setWholesaleAmount(procurementTmp.getProcurementWholesaleAmount());
            stock.setPrescriptionAmount(procurementTmp.getProcurementPrescriptionAmount());
            stock.insertOrUpdate();
        }

        ResultCode resultCode=null;
        if (save&&b){
            resultCode=new ResultCode(1,"入库成功");
        }else{
            resultCode=new ResultCode(0,"入库失败");
        }
        return resultCode;
    }

    @RequestMapping("/mediclineList")
    @ResponseBody
    public Map<String,Object> mediclineList(@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                            String keyword){
        IPage<MedicineInfo> page = new Page<>(pageNum,pageSize);
        QueryWrapper<MedicineInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)){
            wrapper.like("dictionary_type",keyword);
            wrapper.or();
            wrapper.like("medicine_name",keyword);
        }
        IPage<MedicineInfo> result = medicineInfoService.page(page, wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",result.getTotal());
        map.put("rows",result.getRecords());
        return map;
    }

    @RequiresPermissions("procurement:insert")
    @RequestMapping("/procurementInsert")
    @ResponseBody
    public ResultCode procurementInsert(Integer[] medicineInfoIds){
        List<MedicineInfo> medicineInfos = medicineInfoService.listByIds(Arrays.asList(medicineInfoIds));
        for (MedicineInfo medicineInfo : medicineInfos) {
            Procurement procurement = new Procurement();
            procurement.setUnit(medicineInfo.getDictionaryUnit());
            procurement.setSpecs(medicineInfo.getDictionarySpecs());
            procurement.setMedicineName(medicineInfo.getMedicineName());
            procurement.insertOrUpdate();
        }
        return new ResultCode(1,"添加药品成功");
    }

    @RequiresPermissions("procurement:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public ResultCode delete(long procurementId){
        boolean b = procurementService.removeById(procurementId);
        ResultCode code=null;
        if (b){
            code=new ResultCode(1,"删除成功");
        }else{
            code=new ResultCode(0,"删除失败");
        }
        return code;
    }

    @RequestMapping("/toMedicinesSet")
    public String toMedicinesSet(Integer[] procurementIds,Model model){
        StringBuilder stringBuilder = new StringBuilder();
        for (Integer procurementId : procurementIds) {
            stringBuilder.append(procurementId.toString());
            stringBuilder.append(",");
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        System.out.println(stringBuilder);
        model.addAttribute("procurementIds",stringBuilder);
        return "batchSetting";
    }

    @RequiresPermissions("procurement:update")
    @RequestMapping("/MedicinesSet")
    @ResponseBody
    public ResultCode MedicinesSet(String procurementIds,Procurement procurement){
        ArrayList<Procurement> list = new ArrayList<>();
        for (String procurementId : procurementIds.split(",")) {
            Procurement procurement1 = new Procurement();
            procurement1.setProcurementNumber(procurement.getProcurementNumber());
            procurement1.setProcurementPrescriptionPrice(procurement.getProcurementPrescriptionPrice());
            procurement1.setProcurementWholesalePrice(procurement.getProcurementWholesalePrice());
            procurement1.setProcurementId(Long.parseLong(procurementId));
            procurement1.setProcurementWholesaleAmount(procurement.getProcurementNumber()*procurement.getProcurementWholesalePrice());
            procurement1.setProcurementPrescriptionAmount(procurement.getProcurementNumber()*procurement.getProcurementPrescriptionPrice());
            list.add(procurement1);
        }
        boolean b = procurementService.saveOrUpdateBatch(list);
        ResultCode resultCode=null;
        if (b){
            resultCode=new ResultCode(1,"设置成功");
        }else{
            resultCode=new ResultCode(0,"设置失败");
        }
        return resultCode;
    }

}

